import { message } from 'antd'

const baseUrl = 'https://ai.shangou.store'

async function request({ method = 'get', url, data, ...option }) {
  method = method.toUpperCase()

  let optionObj = {
    method,
    ...option
  }

  if (method === 'GET') {
    if (data) {
      let paramsArray = []
      Object.keys(data).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(data[key])))
      if (url.search(/\?/) === -1) {
        typeof data === 'object' && (url += '?' + paramsArray.join('&'))
      } else {
        url += '&' + paramsArray.join('&')
      }
    }
  }

  if (method === 'POST') {
    optionObj.body = JSON.stringify(data)
  }

  try {
    const response = await fetch(baseUrl + url, optionObj)

    const res = await response.json()

    const responseCode = Number(res.code)

    switch (responseCode) {
      case 200:
        // 将返回null统一转成undefined
        return Promise.resolve(res.data ?? undefined)
      default:
        message.destroy()

        if (res.msg) {
          message.error(res.msg)
          return Promise.reject(res.msg)
        }
        break
    }
  } catch (error) {
    message.error(error.toString())

    return Promise.reject(error)
  }
}

export default request
